package com.xyy.ec.qualification.service;

import com.alibaba.fastjson.JSON;
import com.xyy.ec.qualification.enums.TaskEnum;
import com.xyy.ec.qualification.exception.ServiceException;
import com.xyy.ec.qualification.pojo.PopRestDto;
import com.xyy.ec.qualification.pojo.SellerDataConfig;
import com.xyy.ec.qualification.task.TaskHandler;
import com.xyy.ec.qualification.utils.http.RedirectUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;

import static com.xyy.ec.qualification.utils.MergedUrl.mergeUrl;

/**
 * 本地url方式 磁盘名开头
 */
@Slf4j
@Service("local")
public class LocalUrlDataSyncServiceHandel extends DataSyncServiceHandel implements TaskHandler {

    @Override
    public void handleDrugReport(TaskEnum taskEnum) {
        syncErpDataToPop(taskEnum);
    }

    @Override
    public void handleFirstBattalionQualification(TaskEnum taskEnum) {
        syncErpDataToPop(taskEnum);
    }

    /**
     * 判断文件类型后使用不同的请求头
     * @param url
     * @return
     */
    private static String getSuffix(String url) {
        if(url.endsWith(".jpg") || url.endsWith(".jpeg")||url.endsWith(".JPG") || url.endsWith(".JPEG")){
            return "image/jpeg";
        }
        if(url.endsWith(".png") || url.endsWith(".PNG")){
            return "image/png";
        }
        return "";
    }


    @Override
    public List<Map<String, Object>> fileConvert2Url(TaskEnum taskEnum, List<Map<String, Object>> serverResultList) {
        List<Map<String, Object>> newServerResultList = new ArrayList<>();
        if (CollectionUtils.isEmpty(serverResultList)) {
            return newServerResultList;
        }
        //请求头必须设置，否则报错
        Map<String, String> headers = Collections.singletonMap("Content-Type", "application/json;charset=UTF-8");

        Map<String, String> params = Collections.singletonMap("appKey", SellerDataConfig.appKey);

        log.info("{}数据转化开始，待转化数据数量={}", taskEnum.getTaskName(),serverResultList.size());

        for (Map<String, Object> map : serverResultList) {
            try {
                String localUrl  = (String) map.get(taskEnum.getValueField());
                if (StringUtils.isBlank(localUrl)) {
                    log.error("{}地址格式异常，data={}", taskEnum.getTaskName(), JSON.toJSONString(localUrl));
                    continue;
                }

                File file = new File(localUrl);
                if (!file.exists()) {
                    log.error("{}文件不存在,erpCode={}，data={}", taskEnum.getTaskName(),taskEnum.getValueField(),JSON.toJSONString(localUrl));
                    continue;
                }

                String suffix = getSuffix(localUrl);
                if (suffix.isEmpty()) {
                    log.error("文件类型不支持，data={}", localUrl);
                    continue;
                }

                MediaType mediaType = MediaType.parse(suffix);

                log.info("当前 {} 任务数据转化中,erpCode={},文件类型={}", taskEnum.getTaskName(),map.get(taskEnum.getQueryField()), suffix);

                String url = RedirectUtil.doPostByFrom(getUploadUrl(), headers, params, file.getName(), file, mediaType, RedirectUtil.READ_TIMEOUT_THREE_MINUTES);
                PopRestDto restDto = JSON.parseObject(url, PopRestDto.class);
                if(Objects.isNull(restDto) || ! restDto.getStatus() || StringUtils.isBlank(restDto.getData())){
                    throw new ServiceException("文件上报异常");
                }

                Map<String, Object> newMap = new HashMap<>(map);
                newMap.put(taskEnum.getValueField(), restDto.getData());
                newServerResultList.add(newMap);

            } catch (Exception e) {
                log.info("{}数据转化异常，data={}", taskEnum.getTaskName(), JSON.toJSONString(map));
            }
        }
        return mergeUrl(newServerResultList,taskEnum.getTaskId());
    }
}
